package com.cash.app.utils

import android.annotation.SuppressLint
import android.content.pm.ApplicationInfo
import android.os.Build
import com.cash.app.application.MyApplication
import com.cash.app.manager.model.ShareAppInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object AppListUtils {

    private const val TAG = "AppListUtils"

    @SuppressLint("QueryPermissionsNeeded")
    suspend fun getInstalledApps(): List<ShareAppInfo> = withContext(Dispatchers.IO) {
        val pm = MyApplication.appContext.packageManager
        val packages = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            try {
                pm.getInstalledPackages(0)
            } catch (e: Exception) {
                TLog.e("getInstalledApps error: ${e.message}", TAG)
                emptyList()
            }
        } else {
            pm.getInstalledPackages(0)
        }

        packages.map { packageInfo ->
            ShareAppInfo(
                share_app_name = try {
                    packageInfo.applicationInfo?.loadLabel(pm).toString()
                    //TLog.d("name=$name", TAG)
                    //name
                } catch (e: Exception) {
                    ""
                },
                share_package_name = packageInfo.packageName,
                share_in_time = try {
                    packageInfo.firstInstallTime.toInt()
                } catch (e: Exception) {
                    0
                },
                share_up_time = try {
                    packageInfo.lastUpdateTime.toInt()
                } catch (e: Exception) {
                    0
                },
                share_version_code = try {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        packageInfo.longVersionCode.toInt()
                    } else {
                        packageInfo.versionCode
                    }
                } catch (e: Exception) {
                    0
                },
                share_flags = try {
                    packageInfo.applicationInfo?.flags ?: 0
                } catch (e: Exception) {
                    0
                },
                share_app_type = if ((packageInfo.applicationInfo?.flags?.and(ApplicationInfo.FLAG_SYSTEM)) != 0) 1 else 0
            )
        }
    }
} 